<template></template>

<script>
import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'
import { parseTime } from '@/utils/index'
let fileName = '' // 文件名
let loadingInstance = {
  close: function() {}
}
const timeout = 60000 // 请求超时，适当修改
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout
})
// http request 拦截器
service.interceptors.request.use(
  config => {
    loadingInstance = Loading.service({
      lock: true,
      text: '正在导出，请耐心等待.....',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    config.headers['Authorization'] = store.getters.token || ''
    return config
  },
  error => {
    window.console.error(error)
    return Promise.reject(error)
  }
)

// http response 拦截器
service.interceptors.response.use(
  res => {
    loadingInstance.close()
    processData(res.data)
    res.data = ''
    return res
  },
  error => {
    loadingInstance.close()
    window.console.error(error)
    return Promise.resolve(error.response)
  }
)
/*
 *  处理文档数据
 * */
function processData(data) {
  if (!data) {
    return
  }
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(new Blob([data]), fileName)
  } else {
    const url = window.URL.createObjectURL(new Blob([data]))
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

/*
 *  通过 axios ajax 请求资源
 * */
function ajax(url, method, data = {}) {
  let paramStr = ''
  for (const p in data) {
    paramStr += '&' + p + '=' + data[p]
  }
  paramStr && (url += '?' + paramStr.slice(1))
  service({
    method,
    url,
    data: data,
    responseType: 'blob'
  })
    .then(res => {
      res = res || { status: 404, statusText: '服务器出错！' }
      if (res.status === 200 || res.status === 304 || res.status === 400) {
        return res
      }
    })
    .catch(err => {
      Message({
        message: `导出有问题,${err}`,
        type: 'error',
        duration: 2 * 1000
      })
      window.console.log('代码有问题：', err)
    })
}

export default {
  name: 'DownLoad',
  props: {
    url: {
      type: String,
      default: ''
    },
    excelName: {
      type: String,
      default: ''
    },
    fileName: {
      type: String,
      default: ''
    },
    params: {
      type: Object,
      default: function() {
        return {}
      }
    },
    method: {
      type: String,
      default: 'post'
    }
  },
  methods: {
    downLoad(params) {
      this.$nextTick(() => {
        // 延迟下载,保证params参数获取
        const nowTime = parseTime(new Date(), '{mm}-{dd} {hh}_{ii}_{ss}')
        Object.assign(this.params, params)
        let excelName = this.excelName
        if (!excelName.includes('.xls')) {
          excelName += '.xlsx'
        }
        fileName = this.fileName || excelName || 'excel.xlsx'
        fileName = fileName.replace(/(\.\w+)$/, '(' + nowTime + ')$1')
        this.params.excelName && delete this.params.excelName
        this.params.fileName && delete this.params.fileName
        ajax(this.url, this.method, this.params)
      })
    }
  }
}
</script>

<style scoped>
</style>
